package br.com.j7.jdesk.ui.bean;

import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

import br.com.j7.jdesk.persistence.entity.Users;
import br.com.j7.jdesk.persistence.entity.UsersGroups;
import br.com.j7.jdesk.persistence.repository.UserGroupRepository;
import br.com.j7.jdesk.persistence.repository.UserRepository;
import br.com.j7.jdesk.persistence.repository.impl.UserGroupRepositoryImpl;
import br.com.j7.jdesk.persistence.repository.impl.UserRepositoryImpl;

/**
 * 
 * @author Edivando Alves
 *
 */
@ManagedBean
@RequestScoped
public class UsersBean extends WebContext implements Bean{
	
	private Users user = new Users();
	private List<UsersGroups> usersGroups;
	private List<Users> users;
	private UserRepository repository;
	private UserGroupRepository userGroupRepository;
	
	public UsersBean() {
		repository = new UserRepositoryImpl();
		userGroupRepository = new UserGroupRepositoryImpl();
	}
	
	@Override
	public String adicionar(){	
		try {
			if(!user.getCdConfirmPassword().equals(user.getCdPassword())){
				return "userForm";
			}
			if(user.getIdUser() == null || user.getIdUser().equals(0)){
				user.setIdUser(null);
				repository.add(user);
				addMessage("ui.mobile.user.add", user.getCdUser());
			}else {
				repository.update(user);
				addMessage("ui.mobile.user.update", user.getCdUser());
			}
			user = new Users();
			this.users = null;
			return "user";
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	@Override
	public String remover(){
		try {
			if( repository.remove(user) ){
				addMessage("ui.mobile.user.remove", user.getCdUser());
				users = null;
				user = null;
			}
			return "user";
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public List<Users> getUsers(){
		try {
			if(this.users == null){
				this.users = repository.listByEnterprise(getSessionEnterprise());
			}
			return this.users;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public Users getUser() {
		return user;
	}
	
	public void setUser(Users user) {
		this.user = user;
	}
	
	public List<UsersGroups> getUsersGroups() {
		try {
			if (usersGroups == null) {
				usersGroups = userGroupRepository.listByEnterprise(getSessionEnterprise());
			}
			return usersGroups;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	@Override
	public String toForm(){
		return "userForm";
	}
	
	@Override
	public String toList() {
		user = new Users();
		return "user";
	}

}
